package ext.tianma.bom.service.partQuantity;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wt.util.WTProperties;
import ext.tianma.util.TMUtil;

public class QuantityConfig {

	private static String FILEPATH ;
	private static File file ;
	private static Long lastModifyTime = 0L;
	private static String THOME ;
	
	private static Map<String, String> map1 = new LinkedHashMap<String, String>();
	private static Map<String, Map<String, String>> map2 = new LinkedHashMap<String, Map<String, String>>();
	private static Map<String, String> map3 = new LinkedHashMap<String, String>();
	private static Map<String, Map<String, String>> map4 = new LinkedHashMap<String, Map<String, String>>();
	private static Map<String, String> map5 = new LinkedHashMap<String, String>();
	private static String MAXNUM = "max";
	private static String TM_STRUCTURE_OTHER = "TM_Structure_Other";
	
	private static final Logger logger = LoggerFactory.getLogger(QuantityConfig.class);
	
	static {
		try {
			WTProperties wtproperties = WTProperties.getLocalProperties();
			THOME = wtproperties.getProperty("wt.codebase.location");
			FILEPATH = THOME + File.separator + "ext" +
					File.separator + "tianma" + File.separator + "bom" + File.separator +
					"service" + File.separator + "partQuantity" + File.separator + "config" + File.separator + "QuantityConfig.xml";
			
//			FILEPATH = "\\\\192.168.119.136\\Windchill\\codebase\\ext\\tianma\\bom\\service\\partQuantity\\config\\QuantityConfig.xml";
			
			file = new File(FILEPATH);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		getQuantity("范围1", "LV1");
		
		getLevel("范围1", new BigDecimal("2000.001"));
		
		getUsableRange("消费品","LTPS LCD","厦门G6/G5.5");
	}
	
	//根据范围、等级，得到阈值用量
	public static BigDecimal getQuantity(String range, String level) {
		load();
		logger.info("------------------------------");
		logger.info("总用量1配置：" + map1);
		String num = map1.get(range + "_" + level);
		logger.info(range + "_" + level + "的值：" + num);
		return new BigDecimal(num);
	}
	
	//根据范围、用量，得到等级
	public static String getLevel(String range, BigDecimal quantity) {
		load();
		String level = "";
		logger.info("------------------------------");
		logger.info("总用量2配置：" + map2);
		Map<String, String> _map2 = map2.get(range);
		logger.info(range + "的配置情况：" + _map2);
		BigDecimal temp = new BigDecimal(0);
		
		/** 
		 * 方式二：使用一个固定标识，作为封顶判断
		 * 10: temp<quantity <=10,
		 * 100: temp<quantity <=100,
		 * 1000: temp<quantity <=1000,
		 * max: quantity > 1000
		 */
		for(Entry<String, String> m : _map2.entrySet()) {
			String key = m.getKey();
			String value = m.getValue();
			if(!MAXNUM.equals(key)) {
				BigDecimal _key = new BigDecimal(key);
				//quantity大于temp， quantity小于等于value ： 此时在范围阈值区间内(0 < x ≤ 1000)
				if(quantity.compareTo(temp) == 1 && quantity.compareTo(_key) < 1) {
					logger.info(range + "下" +quantity + "对应的等级为1:" + value);
					level = value;
					break;
				}
				temp = _key;
			}
		}
		//quantity大于temp ： 此时大于范围阈值最大值(x > 1000)
		if(quantity.compareTo(temp) == 1) {
			logger.info(range + "下" +quantity + "对应的等级为2:" + _map2.get(MAXNUM));
		}
		return level;
	}
	
	/**
	 * 得到配置的用户信息
	 * @return
	 * @author xucr
	 * @CreateDate 2020年11月18日
	 */
	public static String getUserName() {
		load();
		logger.info("------------------------------");
		logger.info("用户信息：" + map3);
		String userName = map3.get("userName");
		return userName;
	}
	/**
	 * 根据成品属性，匹配使用范围
	 * @param projectBelong
	 * @param technicaltypes
	 * @param cellCutOrigin
	 * @author xucr
	 * @CreateDate 2020年11月6日
	 */
	public static Map<String, String> getUsableRange(String projectBelong,String technicaltypes ,String cellCutOrigin) {
		load();
		logger.info("------------------------------");
		logger.info("总用量4配置：" + map4);
		Map<String, String> ranges = map4.get(projectBelong + "_" + technicaltypes + "_" + cellCutOrigin);
		if(null != ranges && ranges.size() > 0) {//有内容
			logger.info("1>>>" + ranges);
		} else {//特殊情况：某个产品归属下，其technicaltypes的值不在配置当中时
			ranges = map4.get(projectBelong + "_" + TM_STRUCTURE_OTHER + "_" + cellCutOrigin);
			logger.info("2>>>" + ranges);
		}
		return ranges;
	}
	
	/**
	 * 获取所有的使用范围
	 * @return
	 * @author xucr
	 * @CreateDate 2020年11月6日
	 */
	public static Map<String, String> getUsableRange() {
		load();
		return map5;
	}
	
	@SuppressWarnings("unchecked")
	private static void load() {
		logger.info("FILEPATH>>>" + FILEPATH);
		if(file.lastModified() > lastModifyTime) {
			logger.info("------重新解析配置------");
			map1.clear();
			map2.clear();
			map3.clear();
			map4.clear();
			map5.clear();
			
			SAXReader reader = new SAXReader();
			try {
				Document document = reader.read(file);
				
				//解析用量阈值
				List<Element> element1 = document.selectNodes("//Range");
				if(null != element1 && element1.size() > 0) {
					Map<String, String> _map2 = null;
					for(Element e : element1) {
						_map2 = new LinkedHashMap<String, String>();
						String key = e.attributeValue("key"); //范围内部名称
						String name = e.attributeValue("name"); //范围显示名称
						map5.put(key, name);
						List<Element> l = e.elements();
						for(int i = 0 ; i < l.size(); i++) {
							Element _e = (Element) l.get(i);
							String levelKey = _e.attributeValue("levelKey");
							String num = _e.attributeValue("num");
							
							map1.put(key + "_" + levelKey, num);
							_map2.put(num, levelKey);
						}
						map2.put(key, _map2);
					}
				}
				
				//解析用户:仅有一个用户
				List<Element> element2 = document.selectNodes("//User");
				if(null != element2 && element2.size() > 0) {
					for(Element e : element2) {
						String userName = e.attributeValue("userName"); //用户
						map3.put("userName", userName);
					}
				}
				
				//解析八大范围
				List<Element> element3 = document.selectNodes("//Scope");
				if(null != element3 && element3.size() > 0) {
					Map<String, String> ranges = null;
					for(Element e : element3) {
						String name = e.attributeValue("name"); //产品归属 
						List<Element> l = e.elements();
						for(int i = 0 ; i < l.size(); i++) {
							ranges = new Hashtable<String, String>();
							Element _e = (Element) l.get(i);
							String key1 = TMUtil.conversion(_e.attributeValue("key1"));
							String key2 = TMUtil.conversion(_e.attributeValue("key2"));
							String rangeValue = TMUtil.conversion(_e.attributeValue("RangeValue"));
							String rangeKey = TMUtil.conversion(_e.attributeValue("RangeKey"));
							
							ranges.put("key", rangeKey);
							ranges.put("value", rangeValue);
							map4.put(name + "_" + key1 + "_" + key2, ranges);
						}
					}
				}
				
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			lastModifyTime = file.lastModified();
		}
	}
}
